﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace TaoTaoKeForQqWeibo
{
    internal class DataObj
    {
        static ITopClient client = new DefaultTopClient(
                Setting.Default.url, Setting.Default.appkey, Setting.Default.appsecret);

        public static ITopClient TopClient
        {
            get
            {
                return client;
            }
        }

        public static bool WeatherFetch { get; set; }

        internal static List<taobaoke_item> getdata(long cid, int num)
        {
            List<taobaoke_item> products = new List<taobaoke_item>();

            try
            {
                TaobaokeItemsGetRequest req = new TaobaokeItemsGetRequest();
                req.Fields = "title,pic_url,click_url";
                req.Pid = Setting.Default.pid;
                req.Cid = cid;
                req.PageNo = num;
                req.PageSize = 40L;
                TaobaokeItemsGetResponse response = TopClient.Execute(req);
                XElement newElement = XElement.Parse(response.Body);
                if (newElement.Name == ("error_response"))
                {

                }
                else
                {
                    foreach (var item in newElement.Descendants("taobaoke_item"))
                    {
                        taobaoke_item p = new taobaoke_item()
                        {
                            title = item.Element("title").Value,
                            pic_url = item.Element("pic_url").Value,
                            click_url = item.Element("click_url").Value
                        };

                        products.Add(p);
                    }
                }
            }
            catch (Exception ex)
            {
                LogError.LogErrorToFile(ex);
            }

            return products;
        }

        internal static void FetchItems(Action<taobaoke_item> action)
        {
            while (WeatherFetch)
            {
                var dc = new DataHelperDataContext();

                var item_cats = (from cats
                                   in dc.item_cats
                                 where cats.is_parent == "false" && cats.has_get == false
                                 select cats)
                               .Take<item_cat>(1);

                var cat = item_cats.Count<item_cat>() == 1 ? item_cats.First<item_cat>() : null;

                if (cat == null)
                {
                    throw new Exception("没有类型可以获取数据！");
                }

                var cidLong = long.Parse(cat.cid);

                for (int i = Setting.Default.page_no; i < 11; i++)
                {
                    if (WeatherFetch)
                    {

                        foreach (var item in DataObj.getdata(cidLong, Setting.Default.page_no))
                        {
                            dc.taobaoke_items.InsertOnSubmit(item);
                            action(item);
                        }

                        dc.SubmitChanges();
                        Setting.Default.page_no++;
                        Setting.Default.Save();
                        Console.WriteLine(Setting.Default.page_no);
                        Thread.Sleep(2000);
                    }
                    else break;
                }

                cat.has_get = true;
                dc.SubmitChanges();
                Setting.Default.page_no = 1;
                Setting.Default.Save();

                Thread.Sleep(5000);
            }

        }

        internal static void getItemCats(int parentCid)
        {
            Thread.Sleep(2000);

            try
            {
                ItemcatsGetRequest req = new ItemcatsGetRequest();
                req.Fields = "cid,parent_cid,name,is_parent";
                req.ParentCid = parentCid;
                ItemcatsGetResponse response = client.Execute(req);
                XElement newElement = XElement.Parse(response.Body);
                if (newElement.Name == ("error_response"))
                {

                }
                else
                {
                    DataHelperDataContext dataHelper = new DataHelperDataContext();
                    foreach (var item in newElement.Descendants("item_cat"))
                    {
                        dataHelper.item_cats.InsertOnSubmit(new item_cat()
                               {
                                   cid = item.Element("cid").Value,
                                   name = item.Element("name").Value,
                                   is_parent = item.Element("is_parent").Value,
                                   parent_cid = item.Element("parent_cid").Value
                               });

                        if (item.Element("is_parent").Value == "true")
                        {
                            getItemCats(int.Parse(item.Element("cid").Value));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
